package com.zygh.questionnairesurvey.server;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zygh.questionnairesurvey.common.CommonResult;
import com.zygh.questionnairesurvey.entity.UserRole;
import com.zygh.questionnairesurvey.mapper.UserRoleMapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

import static cn.hutool.core.date.DateUtil.now;

@Service
public class UserRoleService extends ServiceImpl<UserRoleMapper, UserRole> {

    @Resource
    private UserRoleMapper userRoleMapper;

    /**
     * 查询所有记录
     *
     * @return 返回集合，没有返回空List
     */
    public CommonResult listAll(Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<UserRole> userRoles = userRoleMapper.selectList(null);
        if (userRoles.size() > 0) {
            PageInfo<UserRole> pageInfo = new PageInfo<>(userRoles);
            return new CommonResult().success(pageInfo);
        }
        return new CommonResult().validateFailed("查询失败！");
    }


    /**
     * 根据主键查询
     *
     * @param id 主键
     * @return 返回记录，没有返回null
     */
    public CommonResult getById(Integer id) {
        UserRole userRole = userRoleMapper.selectById(id);
        if (userRole != null) {
            return new CommonResult().success(userRole);
        }
        return new CommonResult().validateFailed("查询失败！");
    }

    /**
     * 新增，插入所有字段
     *
     * @param userRole 新增的记录
     * @return 返回影响行数
     */
    public CommonResult insert(UserRole userRole) {
        userRole.setCreatetime(DateUtil.parse(now()));
        int insert = userRoleMapper.insert(userRole);
        if (insert > 0) {
            return new CommonResult().success();
        }
        return new CommonResult().validateFailed("新增失败！");
    }

    /**
     * 修改，修改所有字段
     *
     * @param userRole 修改的记录
     * @return 返回影响行数
     */
    public CommonResult update(UserRole userRole) {
        int insert = userRoleMapper.updateById(userRole);
        if (insert > 0) {
            return new CommonResult().success();
        }
        return new CommonResult().validateFailed("修改失败！");
    }

    /**
     * 删除记录
     *
     * @param id 待删除的记录
     * @return 返回影响行数
     */
    public CommonResult delete(Integer id) {
        int i = userRoleMapper.deleteById(id);
        if (i > 0) {
            return new CommonResult().success();
        }
        return new CommonResult().validateFailed("删除失败！");
    }

}